package com.zhou.framework.helper;

import com.zhou.framework.util.ClassUtil;
import com.zhou.framework.util.ReflectionUtil;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * Bean助手类
 * <p>
 * 现在，BeanHelper相当于一个"Bean容器"。因为在Bean Map中存放了Bean类和Bean实例的映射关系
 * 我们只需要通过调用getBean方法，传入一个Bean类，就能获取Bean实例
 *
 * @author zhouplus [http://my.oschina.net/u/2303497/blog]
 * @date 2016/4/14  17:55
 * @since 1.0.0
 */

public final class BeanHelper {

    /**
     * 定义Bean映射（用于存放Bean类与Bean 实例的映射关系）
     */
    private static final Map<Class<?>, Object> BEAN_MAP = new HashMap<Class<?>, Object>();

    //实例化Bean
    static {
        Set<Class<?>> beanClassSet = ClassHelper.getBeanClassSet();
        for (Class<?> beanClass : beanClassSet) {
            Object obj = ReflectionUtil.newInstance(beanClass);
            BEAN_MAP.put(beanClass, obj);
        }
    }

    /**
     * 获取Bean映射
     */
    public static Map<Class<?>, Object> getBeanMap() {
        return BEAN_MAP;
    }

    /**
     * 获取Bean实例
     */
    @SuppressWarnings("unchecked")
    public static <T> T getBean(Class<T> cls) {
        if (!BEAN_MAP.containsKey(cls)) {
            throw new RuntimeException("can not get bean by class: " + cls);
        }
        return (T) BEAN_MAP.get(cls);
    }

    /**
     * 设置Bean实例
     *
     * @author zhouplus [http://my.oschina.net/u/2303497/blog]
     * @since 1.0.0
     * @date  2016/4/18  15:31
     */

    public static void setBean(Class<?> cls, Object obj){
        BEAN_MAP.put(cls, obj);
    }

}
